﻿@page "/Admin/Friends"
@using Moments.Model
@using Moments.Service
@inject IFreeSql Db
@inject FriendService FriendService
@inject GatherService GatherService
@inject NavigationManager NavigationManager
<MCard Color="white lighten-4 mb-2" Style="border-radius: 12px!important;padding: 6px 0;" Elevation="0" Flat Tile>
    <MToolbar Dense Elevation="0">
        <MButton class="ma-2 white--text"
                 OnClick="() => _addModal = true"
                 Color="blue-grey">
            添加新朋友
            <MIcon Right Dark>
                fa:fas fa-plus
            </MIcon>
        </MButton>
        <MButton class="ma-2 white--text"
                 Color="blue-grey"
                 OnClick="Clear">
            清空数据
            <MIcon Right Dark>
                fa:fas fa-trash
            </MIcon>
        </MButton>
        <MSpacer></MSpacer>
        <MButton class="ma-2 white--text"
                 Color="blue-grey"
                 OnClick="async Task() => { await Export(); }">
            导出数据
            <MIcon Right Dark>
                fa:fas fa-download
            </MIcon>
        </MButton>
        <MButton class="ma-2 white--text"
                 Color="blue-grey">
            导入数据
            <div style="opacity: 0;position: absolute;left: 0;right:0">
                <InputFile OnChange="@Import" style="width: 100%"/>
            </div>
            <MIcon Right Dark>
                fa:fas fa-upload
            </MIcon>
        </MButton>
    </MToolbar>
</MCard>
<MDataTable FixedRight
            Headers="_headers"
            Items="_friends"
            Width="@("100%")"
            ItemKey="r => r.FriendId.ToString()"
            Search="@_search"
            Class="elevation-1">
    <TopContent>
        <MTextField @bind-Value="_search"
                    Label="搜索"
                    Class="mx-4">
        </MTextField>
    </TopContent>
    <ItemColContent>
        @if (context.Header.Value == "actions")
        {
            <MIcon Small
                   Class="mr-1"
                   OnClick="() => GatherItem(context.Item)">
                mdi:mdi-rss
            </MIcon>
            <MIcon Small
                   Class="mr-1"
                   OnClick="() => EditItem(context.Item)">
                mdi:mdi-pencil
            </MIcon>
            <MIcon Small
                   OnClick="() => DeleteItem(context.Item)">
                mdi:mdi-delete
            </MIcon>
        }
        else
        {
            @context.Value
        }
    </ItemColContent>
</MDataTable>
<MDialog @bind-Value="_dialogEdit"
         MaxWidth="500">
    <MCard>
        <MCardTitle>
            <span class="text-h5">编辑</span>
        </MCardTitle>
        <MCardText>
            <MContainer>
                <MRow>
                    <MCol Cols="12"
                          Sm="4"
                          Md="4">
                        <MTextField @bind-Value="_editedItem.Name"
                                    Label="博主名称">
                        </MTextField>
                    </MCol>
                    <MCol Cols="12"
                          Sm="4"
                          Md="4">
                        <MTextField @bind-Value="_editedItem.Description"
                                    Label="简介">
                        </MTextField>
                    </MCol>
                    <MCol Cols="12"
                          Sm="4"
                          Md="4">
                        <MTextField @bind-Value="_editedItem.Email"
                                    Label="邮箱">
                        </MTextField>
                    </MCol>
                    <MCol Cols="12"
                          Sm="12"
                          Md="12">
                        <MTextField @bind-Value="_editedItem.Avatar"
                                    Label="头像">
                        </MTextField>
                    </MCol>
                    <MCol Cols="12"
                          Sm="4"
                          Md="4">
                        <MSelect Items="Enum.GetNames(typeof(Rule))"
                                 @bind-Value="@_editedItem.Rule"
                                 ItemText="u => u"
                                 ItemValue="u => (Rule)Enum.Parse(typeof(Rule), u)"
                                 Label="规则"
                                 Dense
                                 Filled
                                 HideDetails="@("auto")">
                        </MSelect>
                    </MCol>
                    <MCol Cols="12"
                          Sm="6"
                          Md="8">
                        <MTextField @bind-Value="_editedItem.Feed"
                                    Label="Feed">
                        </MTextField>
                    </MCol>

                    <MCol Cols="12"
                          Sm="12"
                          Md="12">
                        <MTextField @bind-Value="_editedItem.Link"
                                    Label="链接">
                        </MTextField>
                    </MCol>

                    <MCol Cols="12"
                          Sm="12"
                          Md="12">
                        <MSelect Items="Enum.GetNames(typeof(FriendType))"
                                 @bind-Value="@_editedItem.FriendType"
                                 ItemText="u => u"
                                 ItemValue="u => (FriendType)Enum.Parse(typeof(FriendType), u)"
                                 Label="类别"
                                 Dense
                                 Filled
                                 HideDetails="@("auto")">
                        </MSelect>
                    </MCol>
                </MRow>
            </MContainer>
        </MCardText>
        <MCardActions>
            <MSpacer></MSpacer>
            <MButton Color="blue darken-1"
                     Text
                     OnClick="Close">
                取消
            </MButton>
            <MButton Color="blue darken-1"
                     Text
                     OnClick="Save">
                保存
            </MButton>
        </MCardActions>
    </MCard>
</MDialog>
<MDialog @bind-Value="_dialogDelete" MaxWidth="500">
    <MCard>
        <MCardTitle Class="text-h5">你确定要删除当前的朋友?</MCardTitle>
        <MCardActions>
            <MSpacer></MSpacer>
            <MButton Color="blue darken-1" Text OnClick="CloseDelete">取消</MButton>
            <MButton Color="blue darken-1" Text OnClick="DeleteItemConfirm">确定</MButton>
            <MSpacer></MSpacer>
        </MCardActions>
    </MCard>
</MDialog>

@code {

    private readonly List<DataTableHeader<Friend>> _headers = new()
    {
        new() { Text = "昵称", Value = nameof(Friend.Name) },
        new() { Text = "类别", Value = nameof(Friend.FriendType) },
        new() { Text = "链接", Value = nameof(Friend.Link) },
        new() { Text = "Feed", Value = nameof(Friend.Feed) },
        new() { Text = "操作", Value = "actions", Sortable = false, Width = "100px", Align = DataTableHeaderAlign.Center, }
    };

    private bool _dialogEdit;
    private bool _dialogDelete;
    private Friend _editedItem = new();
    private Friend _delItem = new();

    void Close()
    {
        _dialogEdit = false;
        _editedItem = new Friend();
    }

    async Task Save()
    {
        await Db.Update<Friend>()
            .SetSource(_editedItem)
            .ExecuteAffrowsAsync();
        Close();
    }

    void EditItem(Friend item)
    {
        _editedItem = item;
        _dialogEdit = true;
    }

    void DeleteItem(Friend item)
    {
        _delItem = item;
        _dialogDelete = true;
    }

    async Task DeleteItemConfirm()
    {
        await Db.Delete<Friend>()
            .Where(x => x.FriendId == _delItem.FriendId)
            .ExecuteAffrowsAsync();
        _friends.Remove(_delItem);
        CloseDelete();
    }

    void CloseDelete()
    {
        _dialogDelete = false;
        _editedItem = new();
    }

}

<PModal @bind-Value="_addModal"
        FormModel="_add"
        Persistent
        Title="添加朋友"
        Width="500"
        OnSave="Add"
        OnCancel="() => { _addModal = false; }">
    <MRow>
        <MCol Cols="12">
            <MTextField @bind-Value="_add.Name"
                        Label="博主名称"
                        Dense
                        Outlined
                        HideDetails="@("auto")"/>
        </MCol>
        <MCol Cols="12">
            <MTextField @bind-Value="_add.Avatar"
                        Label="头像"
                        Dense
                        Outlined
                        HideDetails="@("auto")"/>
        </MCol>
        <MCol Cols="12">
            <MTextField @bind-Value="_add.Description"
                        Label="简介"
                        Dense
                        Outlined
                        HideDetails="@("auto")"/>
        </MCol>
        <MCol Cols="12">
            <MTextField @bind-Value="_add.Email"
                        Label="邮箱"
                        Dense
                        Outlined
                        HideDetails="@("auto")"/>
        </MCol>
        <MCol Cols="12">
            <MTextField @bind-Value="_add.Link"
                        Label="链接"
                        Dense
                        Outlined
                        HideDetails="@("auto")"/>
        </MCol>
        <MCol Cols="12">
            <MSelect Items="Enum.GetNames(typeof(Rule))"
                     @bind-Value="@_add.Rule"
                     ItemText="u => u"
                     ItemValue="u => (Rule)Enum.Parse(typeof(Rule), u)"
                     Label="规则"
                     Dense
                     HideDetails="@("auto")"
                     Outlined>
            </MSelect>
        </MCol>
        <MCol Cols="12">
            <MTextField @bind-Value="_add.Feed"
                        Label="Feed"
                        Dense
                        Outlined
                        HideDetails="@("auto")"/>
        </MCol>
        <MCol>
            <MButton OnClick="GetSiteInfo" Class="ma-1">
                Feed获取信息
            </MButton>
            <MButton OnClick="GetAvatar" Class="ma-1">
                邮箱获取头像
            </MButton>
        </MCol>

    </MRow>
</PModal>

@code {
    List<Friend> _friends = new();
    Friend _add = new();
    bool _addModal;
    string? _search;

    protected override async Task OnInitializedAsync()
    {
        _friends = await Db.Select<Friend>().ToListAsync();
    }

    async Task Add()
    {
        var id = await Db.Insert<Friend>()
            .AppendData(_add)
            .ExecuteIdentityAsync();
        _add.FriendId = int.Parse(id.ToString());
        _friends.Add(_add);
        _add = new Friend();
        _addModal = false;
    }

    void GatherItem(Friend item)
    {
        GatherService.GatherRssItem(item);
        AdminLayout.PushSnackbars(AlertTypes.Info, item.Name + ": 采集成功！");
    }


    async Task Export()
    {
        AdminLayout.PushSnackbars(AlertTypes.Info, "正在导出数据中，请稍后···");
        var path = await FriendService.Export();
        AdminLayout.PushSnackbars(AlertTypes.Info, "数据导出成功,即将下载！");
        NavigationManager.NavigateTo(path, true);
    }

    async Task Import(InputFileChangeEventArgs e)
    {
        var file = e.GetMultipleFiles().First();
        await FriendService.Import(file.OpenReadStream());
        AdminLayout.PushSnackbars(AlertTypes.Info, "导入成功，请刷新查看！");
    }

    void Clear()
    {
        FriendService.DelAll();
        AdminLayout.PushSnackbars(AlertTypes.Info, "清空数据成功，请刷新！");
    }

    async Task GetSiteInfo()
    {
        if (_add.Feed is null)
        {
            AdminLayout.PushSnackbars(AlertTypes.Error, "请先填写Feed链接！");
            return;
        }
        var siteInfo = await GatherService.GetRssSiteInfo(_add.Feed);
        _add.Name = siteInfo["title"];
        if (siteInfo["link"] is null || siteInfo["link"]?.Length == 0)
        {
            _add.Link = siteInfo["id"];
            _add.Description = siteInfo["subtitle"];
        }
        else
        {
            _add.Link = siteInfo["link"];
            _add.Description = siteInfo["description"];
        }
    }


    void GetAvatar()
    {
        if (_add.Email is null)
        {
            AdminLayout.PushSnackbars(AlertTypes.Error, "请先填写邮箱！");
            return;
        }
        _add.Avatar = _add.Email.Contains("@qq.com") ? $"https://q1.qlogo.cn/g?b=qq&nk={_add.Email.Replace("@qq.com", "")}&s=100" : $"https://gravatar.loli.net/avatar/{Utils.Md5(_add.Email)}?s=100&r=g";
    }


}